package com.hujf.gameserver.netty;

import com.hujf.gameserver.service.UserService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Hujf
 * @title: RegesterHandler
 * @date 2021/2/15 0015下午 7:58
 * @description: TODO
 */
@Component
public class RegesterHandler extends SimpleChannelInboundHandler {

    private static UserService userService;
    //统一管理通道
    private final static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Autowired
    public void setChatService(UserService userService) {
        RegesterHandler.userService = userService;
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        String m = (String) msg;
        String  []ss= m.split("&");
        if(ss.length==1){
            System.out.println("到这了");
            channelGroup.writeAndFlush(m);
        }else if(ss[0].equals("1")) {
            //插入数据库
            int num = userService.addUser(ss[1], ss[2]);
            if (num > 0) {
                System.out.println("创建");
                ctx.writeAndFlush("注册成功");
            } else {
                throw new RuntimeException("添加用户失败");
            }
        }else{
            //登录逻辑
            ctx.writeAndFlush("登录成功");
        }

    }

//    @Override
//    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("响应");
//
//    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.add(channel);
    }
}
